import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/store'
// 组件按需导入
const Home = () => import('../views/Home.vue')
const Login = () => import('@/views/login/index.vue')
const Layout = () => import('@/views/layout')

const Index = () => import('@/views/index')
const Articles = () => import('@/views/articles')
const AddArticle = () => import('@/views/addArticle')
const EditArticle = () => import('@/views/editArticle')
const Image = () => import('@/views/image')
const Comment = () => import('@/views/comment')
const Fans = () => import('@/views/fans')
const Setting = () => import('@/views/setting')
const NotFound = () => import('@/views/notFound')

// 处理新版router异常
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => (console.warn(err)))
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/test',
    name: 'Home',
    component: Home
  },
  // 基础架构组件
  {
    path: '/',
    // name: 'Layout',
    component: Layout,
    // redirect: { name: 'index' },
    children: [
      {
        path: '/',
        name: 'index',
        component: Index
        // beforeEnter: (to, from, next) => {
        //   // ...
        //   console.log('2. index')
        //   next()
        // }
      },
      {
        path: '/articles',
        name: 'articles',
        component: Articles
      },
      {
        path: '/addArticle',
        name: 'addArticle',
        component: AddArticle
      },
      {
        path: '/editArticle/:id',
        name: 'editArticle',
        component: EditArticle
      },
      {
        path: '/image',
        name: 'image',
        component: Image
      },
      {
        path: '/comment',
        name: 'comment',
        component: Comment
      },
      {
        path: '/fans',
        name: 'fans',
        component: Fans
      },
      {
        path: '/setting',
        name: 'setting',
        component: Setting
      }
    ]
  },
  // 登录
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  // 404页面
  {
    path: '*',
    component: NotFound
  }

]

const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // console.log('1. index')
  const token = getToken()?.token
  if (!token && to.path !== '/login') {
    return next('/login')
  } else if (token && to.path === '/login') {
    return next('/')
  }
  next()
})

export default router
